//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import LeanCloud
//邀请活动
class InviteActViewModel : AiActViewModel {
    
    @Published var items = [InviteRewardBean]()
    @Published var selectedIndex: Int = 0
    @Published var status = ""
    @Published var statusTitle = ""
    
    func doCreateInviteCode() {
        request(isLoading: false) {
            try check(userManager.isLogin(), "未登录")
            if (userManager.getUser()?.inviteCode ?? "")?.isEmpty == false {
                try check(false) {
                    "已经有邀请码了"
                }
            }
            
            let bean = InviteBean()
            bean.userId = userManager.getUserId()
            let objectId = try await LeancloudManager.instance.saveToId(todo: bean) ?? ""
            let newBean = try await retry(maxRetries: 3, retryDelayMillis: 100) {
                let query = LCQuery(className: "Invite")
                query.whereKey("objectId", .equalTo(objectId))
                return try await LeancloudManager.instance.getFirst(query: query, modeType: InviteBean.self)
            }
            if let id = newBean?.id {
                let inviteCode = id.generateInviteCode()
                userManager.getUser()?.inviteCode = inviteCode
                //保存用户信息
                try await retry(maxRetries: 3, retryDelayMillis: 100) {
                    if let user = userManager.getUser() {
                        try await LeancloudManager.instance.save(todo: user)
                    }
                }
                //更新邀请码
                try await retry(maxRetries: 3, retryDelayMillis: 100) {
                    if let newBean = newBean {
                        newBean.code = inviteCode
                        try await LeancloudManager.instance.save(todo: newBean)
                    }
                }
            }
        } suc: {
            userManager.update()
        } fail: { _ in
            
        }
    }
    
    func getData(_ isRefresh: Bool = false) {
        var isTest : Bool = false
        requestList(isRefresh: isRefresh) {
            let query = LCQuery(className: "InviteReward")
            query.whereKey("rewardUserId", .equalTo(userManager.getUserId()))
            query.whereKey("sort", .descending) //降序
            query.limit = self.pageSize
            query.skip = self.pageNo * self.pageSize
            let list =  try await LeancloudManager.instance.getList(query: query, modeType: InviteRewardBean.self)
            let listTest :[InviteRewardBean] = [InviteRewardUtils.doTest1(),
                                                InviteRewardUtils.doTest1(),
                                                InviteRewardUtils.doTest2(),
                                                InviteRewardUtils.doTest3(),
                                                InviteRewardUtils.doTest4(),
                                                InviteRewardUtils.doTest5(),
                                                InviteRewardUtils.doTest6(),
                                                InviteRewardUtils.doTest7()]
            isTest = (isRefresh && list.isEmpty && (userManager.user?.inviteUserId ?? "").isEmpty == true)
            let listAll :[InviteRewardBean] = isTest ? listTest : list
            try check(!isRefresh || !listAll.isEmpty, "暂无数据")
            return listAll
        } suc: { list in
            self.status = ""
            self.statusTitle = isTest ? "以下是示例奖励" : ""
            if isRefresh {
                self.items = list
            } else {
                self.items.append(contentsOf: list)
            }
        } fail: {
            self.status = $0.message
        }
    }
    
    //绑定邀请码查询
    func doBindInvite(code: String) {
        request {
            try check(code != userManager.getUser()?.inviteCode, "邀请码不能填写自己的")
            //先获取对方的用户userId
            let query = LCQuery(className: "Invite")
            query.whereKey("code", .equalTo(code))
            let inviteBean = try await LeancloudManager.instance.getFirst(query: query, modeType: InviteBean.self)
            let toUserId = inviteBean?.userId ?? ""
            try check(toUserId.isEmpty == false, "无效邀请码")
            
            
            let queryQQ = LCQuery(className: "InviteReward")
            if let qq = userManager.getUser()?.qq {
                queryQQ.whereKey("qq", .equalTo(qq))
            }
            
            let queryWx = LCQuery(className: "InviteReward")
            if let wx = userManager.getUser()?.wx {
                queryWx.whereKey("wx", .equalTo(wx))
            }
            let queryApple = LCQuery(className: "InviteReward")
            if let apple = userManager.getUser()?.apple {
                queryApple.whereKey("apple", .equalTo(apple))
            }
            let queryReward = try queryQQ.or(queryWx).or(queryApple)
            let inviteReward = try await LeancloudManager.instance.getFirst(query: queryReward, modeType: InviteRewardBean.self)
            let reward : Bool = inviteReward == nil
            return (toUserId, reward)
        } suc: { (toUserId: String, reward: Bool) in
            if (reward) {
                self.doBindInvite(code: code, toUserId: toUserId, reward: true)
            } else {
                showTipsDialog(text: "您的QQ/微信/手机/Apple已经有绑定过其他邀请码，此次绑定将不会获得奖励") {
                    self.doBindInvite(code: code, toUserId: toUserId, reward: false)
                }
            }
        } fail: {
            showTipsDialog(text: $0.message)
        }
    }
    
    //绑定邀请码
    private func doBindInvite(code: String, toUserId: String, reward: Bool) {
        request {
            //绑定邀请者
            try await retry(maxRetries: 3, retryDelayMillis: 100) {
                if let user = userManager.getUser() {
                    user.inviteUserId = toUserId
                    try await LeancloudManager.instance.save(todo: user)
                }
            }
            if (reward) {
                //创建自己的奖励
                try await InviteRewardUtils.doCreateBind()
                //创建对方的奖励
                try await InviteRewardUtils.doCreateBind(toUserId: toUserId)
            }
            //对方增加邀请人数
            try await retry(maxRetries: 3, retryDelayMillis: 100) {
                try await LeancloudManager.instance.incrementKey(className: UserBean().getCloudTable(), objectId: toUserId, key: "inviteCount", value: 1)
            }

        } suc: {
            showToast("成功")
            userManager.update()
            self.getData(true)
        } fail: { _ in
            showToast("绑定失败")
        }
    }
    
    //领取奖励
     func doReceive(bean: InviteRewardBean) {
        request {
            AiChatExt.doAiChatCount(Double(bean.count ?? 0))
            try await retry(maxRetries: 3, retryDelayMillis: 100) {
                bean.reward = true
                try await LeancloudManager.instance.save(todo: bean)
            }
        } suc: {
            showTipsDialog(text: "已领取奖励\(bean.getCountStr())次 回应次数")
            self.getData(true)
        } fail: { _ in
            showToast("领取失败")
        }
    }
    
    
}
